package com.ljj.examisto.ui.fragment

import android.content.Intent
import android.os.Bundle
import android.os.CountDownTimer
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.ljj.examisto.data.adapter.ExamAdapter
import com.ljj.examisto.data.item.ExamItem
import com.ljj.examisto.databinding.FragmentShowerBinding
import com.ljj.examisto.ui.activity.EditExamActivity
import com.ljj.examisto.util.DatabaseHelper
import com.ljj.examisto.util.ExamContract
import java.util.Calendar
import java.util.Locale

class ShowerFragment : Fragment() {
    private lateinit var binding: FragmentShowerBinding
    private lateinit var dbHelper: DatabaseHelper
    private lateinit var examAdapter: ExamAdapter
    private var countdownTimer: CountDownTimer? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initProperty()
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        binding = FragmentShowerBinding.inflate(inflater, container, false)
        if (dbHelper.hasExams()) {
            setupLatestExam()
            if (dbHelper.getExamCount() >= 2)
                setupRestExams()
        }
        return binding.root
    }

    override fun onDestroy() {
        super.onDestroy()
        countdownTimer?.cancel()
    }

    /* 流程函数 */
    private fun initProperty() {
        dbHelper = DatabaseHelper.getInstance(requireContext())
    }

    private fun setupLatestExam() {
        val latestExam = dbHelper.getLatestExam()
        if (latestExam != null && !latestExam.isClosed) {
            try {
                val currentTime = System.currentTimeMillis()
                val showerMain = binding.showerMain
                val examName = latestExam.getString(latestExam.getColumnIndexOrThrow(ExamContract.COLUMN_EXAM_NAME))
                val startTimeLong = latestExam.getLong(latestExam.getColumnIndexOrThrow(ExamContract.COLUMN_START_TIME))
                val setTime = latestExam.getLong(latestExam.getColumnIndexOrThrow(ExamContract.COLUMN_SET_TIME))
                val startTimeStr = startTimeLong.toString()
                if (startTimeStr.length != 12) return
                val year = startTimeStr.substring(0, 4).toInt()
                val month = startTimeStr.substring(4, 6).toInt()
                val day = startTimeStr.substring(6, 8).toInt()
                val hour = startTimeStr.substring(8, 10).toInt()
                val minute = startTimeStr.substring(10, 12).toInt()
                val calendar = Calendar.getInstance().apply {
                    set(year, month - 1, day, hour, minute, 0)
                    set(Calendar.MILLISECOND, 0)
                }
                val startMillis = calendar.timeInMillis
                binding.tvExamName.text = examName
                val remainingTime = startMillis - currentTime
                // 判断是否已过
                if (remainingTime > 0) {
                    val setMillis = startMillis - setTime
                    setCountdown(remainingTime, setMillis)
                } else {
                    binding.tvCountdown.text = "考试已开始"
                }
                showerMain.setOnClickListener {
                    EditExamActivity.start(requireContext(), examName)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            } finally {
                latestExam.close()
            }
        } else {
            binding.tvExamName.text = "暂无考试安排"
            binding.tvCountdown.text = ""
        }
    }

    private fun setupRestExams() {
        val restExams = dbHelper.getRestExam()
        val examsList = mutableListOf<ExamItem>()
        if (restExams != null && !restExams.isClosed) {
            try {
                do {
                    val examName = restExams.getString(
                        restExams.getColumnIndexOrThrow(ExamContract.COLUMN_EXAM_NAME)
                    )
                    val startTime = restExams.getLong(
                        restExams.getColumnIndexOrThrow(ExamContract.COLUMN_START_TIME)
                    )
                    val startTimeStr = formatTime(startTime)
                    examsList.add(ExamItem(examName, startTimeStr))
                } while (restExams.moveToNext())
            } catch (e: Exception) {
                e.printStackTrace()
            } finally {
                restExams.close()
            }
        }
        examAdapter = ExamAdapter(examsList) { examName ->
            val intent = Intent(requireContext(), EditExamActivity::class.java)
            intent.putExtra("EXAM_NAME", examName)
            startActivity(intent)
        }
        binding.showerRest.apply {
            layoutManager = LinearLayoutManager(requireContext())
            adapter = examAdapter
        }
    }

    /* 工具函数 */
    private fun setCountdown(remainingMillis: Long, setMillis: Long) {
        val countdownTextView = binding.tvCountdown
        val countDownProgressBar = binding.cpCountdown
        countdownTimer?.cancel()
        countdownTimer = object : CountDownTimer(remainingMillis, 1000) {
            override fun onTick(restMillis: Long) {
                val totalSeconds = restMillis / 1000
                val hours = totalSeconds / 3600
                val minutes = (totalSeconds % 3600) / 60
                val seconds = totalSeconds % 60
                val timeStr = String.format(Locale.getDefault(), "%02d:%02d:%02d", hours, minutes, seconds)
                countdownTextView.text = timeStr
                val progress = (restMillis.toFloat() / setMillis.toFloat() * 100f).coerceIn(0f, 100f)
                countDownProgressBar.setProgress(progress)
            }
            override fun onFinish() {
                countdownTextView.text = "考试已开始"
            }
        }.start()
    }

    private fun formatTime(timeMillis: Long): String {
        val timeStr = timeMillis.toString()
        if (timeStr.length != 12) return "时间格式错误"
        return try {
            val year = timeStr.substring(0, 4)
            val month = timeStr.substring(4, 6)
            val day = timeStr.substring(6, 8)
            val hour = timeStr.substring(8, 10)
            val minute = timeStr.substring(10, 12)
            "$year-$month-$day $hour:$minute"
        } catch (_: Exception) {
            "时间解析错误"
        }
    }
}